<template>
  <view class="invite-page">
    <!-- 下拉刷新容器 -->
    <scroll-view 
      class="scroll-container" 
      scroll-y 
      refresher-enabled 
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
      :lower-threshold="100"
    >
    
      <!-- 信息面板区域 -->
      <view class="info-panels">
        <!-- 左侧可提现金额面板 -->
        <view class="panel left-panel">
          <view class="panel-title">可提现金额</view>
          <view class="amount">¥{{ inviteStats.withdrawable_amount || '0.00' }}</view>
          <view class="panel-buttons">
            <view class="btn-outline" @click="goToBillDetail">
              <image src="/static/images/invite-bill.png" class="btn-icon" mode="aspectFit"></image>
              <text>账单明细</text>
            </view>
            <view class="btn-primary" @click="goToWithdraw">
              <image src="/static/images/invite-withdraw.png" class="btn-icon" mode="aspectFit"></image>
              <text>提现</text>
            </view>
          </view>
        </view>

        <!-- 右侧邀请信息面板 -->
        <view class="panel right-panel">
          <view class="panel-header">
            <view class="panel-title">邀请信息</view>
            <view class="rules-btn" @click="viewRules">
              <image src="/static/images/invite-rules.png" class="btn-icon" mode="aspectFit"></image>
              <text>规则</text>
            </view>
          </view>
          <view class="stats-grid">
            <view class="stat-row">
              <view class="stat-item">
                <view class="stat-value">{{ inviteStats.invited_users || 0 }}</view>
                <view class="stat-label">邀请人数</view>
              </view>
              <view class="stat-item">
                <view class="stat-value">{{ inviteStats.vip_users || 0 }}</view>
                <view class="stat-label">会员人数</view>
              </view>
            </view>
            <view class="stat-row">
              <view class="stat-item">
                <view class="stat-value">{{ inviteStats.withdrawn_amount || '0.00' }}</view>
                <view class="stat-label">已提现</view>
              </view>
              <view class="stat-item">
                <view class="stat-value">{{ inviteStats.total_commission || '0.00' }}</view>
                <view class="stat-label">累计佣金</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    
      <!-- 佣金返利面板 -->
      <view class="commission-panel">
        <view class="panel-title">
          <view class="title-bar">
            <text>佣金返利</text>
          </view>
        </view>
        <view class="commission-scroll">
          <lsd-seamless-scroll 
            :list="recentCommissionUsers" 
            :speed="30" 
            direction="up"
            :height="commissionScrollHeightPx"
            :itemHeight="commissionItemHeightPx"
            :duplicateGap="commissionDuplicateGapPx"
            class="commission-scroll-container"
          >
            <template v-slot:item="{ item }">
              <view class="commission-item">
                <image class="user-avatar" :src="item.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
                <view class="commission-info">
                  <text class="commission-line">
                    <text class="user-name">{{ item.nickname || '用户' + item.user_id }}</text>
                    <text class="commission-desc">成功获得</text>
                    <text class="commission-amount">{{ item.amount }}</text>
                    <text class="commission-unit">佣金</text>
                  </text>
                </view>
              </view>
            </template>
          </lsd-seamless-scroll>
        </view>
      </view>
    
      <!-- 我的邀请面板 -->
      <view class="invite-panel">
        <view class="panel-title" @click="toggleInviteExpand">
          <view class="title-bar">
            <text>我的邀请</text>
          </view>
          <view class="expand-btn" :class="{ 'expanded': inviteExpanded }">
            <u-icon name="arrow-down" size="20" color="#666"></u-icon>
          </view>
        </view>
        <view class="invite-list" :class="{ 'expanded': inviteExpanded }">
          <view v-for="(item, index) in displayInviteList" :key="index" class="invite-item">
            <image class="user-avatar" :src="item.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
            <view class="invite-row">
              <text class="user-name">{{ item.nickname || '用户' + item.id }}</text>
              <text class="invite-time">{{ formatTime(item.create_time) }}</text>
            </view>
          </view>
          <view v-if="displayInviteList.length === 0" class="empty-state">
            <text>暂无邀请记录</text>
          </view>
        </view>
      </view>

      <!-- 底部间距 -->
      <view class="bottom-space"></view>
    </scroll-view>
    
    <!-- 固定底部邀请按钮 -->
    <view class="fixed-bottom">
      <view class="invite-btn" @click="openInviteModal">立即邀请新用户</view>
    </view>
    
    <!-- 二维码弹窗 -->
    <u-popup :show="showQRCode" mode="center" border-radius="20" width="600rpx" height="700rpx" @close="showQRCode = false">
      <view class="qr-popup">
        <view class="qr-header">
          <view class="qr-title">邀请好友</view>
          <u-icon name="close" size="24" color="#666" @click="showQRCode = false"></u-icon>
        </view>
        <view class="qr-content">
          <canvas canvas-id="invitePoster" :style="posterCanvasStyle"></canvas>
          <view class="qr-desc">长按以识别</view>
        </view>
        <view class="qr-actions">
          <view class="qr-btn" @click="copyInviteCode">复制邀请码</view>
          <view class="qr-btn primary" @click="savePoster">一键保存海报</view>
        </view>
        
      </view>
    </u-popup>
  </view>
</template>

<script>
/**
 * 邀请返利页面
 * @author 王勇程 <laughskydragon@qq.com>
 */
import { getInviteStats, getRecentInviteCommissionUsers, getInviteList, generateInviteCode, getInviteQrcode } from '@/api/invite'
import APP_CONFIG from '@/config'

export default {
  name: 'InvitePage',
  data() {
    return {
      // 邀请统计数据
      inviteStats: {
        withdrawable_amount: 0,
        invited_users: 0,
        vip_users: 0,
        withdrawn_amount: 0,
        total_commission: 0
      },
      // 最近邀请佣金用户（广告）
      recentCommissionUsers: [],
      // 邀请列表
      inviteList: [],
      // 邀请码
      inviteCode: '',
      qrcodeUrl: '',
      // 显示二维码弹窗
      showQRCode: false,
      posterTempPath: '',
      posterSizeRpx: 600,
      // 下拉刷新状态
      refreshing: false,
      commissionScrollHeightPx: (typeof uni !== 'undefined' && typeof uni.upx2px === 'function') ? uni.upx2px(200) : 200,
      commissionItemHeightPx: (typeof uni !== 'undefined' && typeof uni.upx2px === 'function') ? uni.upx2px(60) : 60,
      commissionDuplicateGapPx: (typeof uni !== 'undefined' && typeof uni.upx2px === 'function') ? uni.upx2px(10) : 10,
      
      // 邀请面板展开状态
      inviteExpanded: false,
      // 邀请列表分页
      invitePage: 1,
      invitePageSize: 20,
      inviteHasMore: true,
      // 加载状态
      loading: false
    }
  },
  computed: {
    posterCanvasStyle() {
      return `width: ${this.posterSizeRpx}rpx; height: ${this.posterSizeRpx}rpx;`
    },
    // 显示的邀请列表
    displayInviteList() {
      if (!this.inviteExpanded) {
        return this.inviteList.slice(0, 5)
      }
      return this.inviteList
    }
  },
  onLoad() {

  },
  onShow() {
    this.loadInviteData()
  },
  onUnload() {

  },
  methods: {
    // 加载邀请数据
    loadInviteData() {
      this.loadInviteStats()
      this.loadRecentCommissionUsers()
      this.loadInviteList(true)
    },
    
    // 加载邀请统计
    async loadInviteStats() {
      try {
        const res = await getInviteStats()
        this.inviteStats = res ? res : {}
      } catch (error) {
        console.error('加载邀请统计失败:', error)
      }
    },
    
    // 加载佣金记录
    async loadRecentCommissionUsers() {
      try {
        const res = await getRecentInviteCommissionUsers({ limit: 20 })
        let list = []
        list = res.data || []
        this.recentCommissionUsers = Array.isArray(list) ? list : []
        if (!this.recentCommissionUsers.length) {
          this.recentCommissionUsers = this.buildFallbackCommission(6)
        }
      } catch (error) {
        console.error('加载佣金记录失败:', error)
        this.recentCommissionUsers = this.buildFallbackCommission(6)
      }
    },
    
    // 加载邀请列表
    async loadInviteList(reset = false) {
      if (this.loading) return
      this.loading = true
      try {
        const page = reset ? 1 : this.invitePage
        const res = await getInviteList({ page, limit: this.invitePageSize })
        let list = []
        list = res.list.data || []
        const newList = Array.isArray(list) ? list : []
        if (reset) {
          this.inviteList = newList
          this.invitePage = 1
        } else {
          this.inviteList = this.inviteList.concat(newList)
        }
        const hasMore = typeof res?.data?.has_more !== 'undefined' ? !!res.data.has_more : (newList.length >= this.invitePageSize)
        this.inviteHasMore = hasMore
        if (this.inviteHasMore && !reset) {
          this.invitePage++
        }
      } catch (error) {
        console.error('加载邀请列表失败:', error)
      }
      this.loading = false
    },
    
    // 下拉刷新
    async onRefresh() {
      this.refreshing = true
      await this.loadInviteData()
      setTimeout(() => {
        this.refreshing = false
      }, 1000)
    },
    
    // 触底加载更多
    onLoadMore() {
      if (this.inviteExpanded && this.inviteHasMore && !this.loading) {
        this.invitePage++
        this.loadInviteList()
      }
    },
    
    // 切换邀请面板展开状态
    toggleInviteExpand() {
      this.inviteExpanded = !this.inviteExpanded
    },
    
    
    
    // 生成邀请码
    async generateInviteCode() {
      try {
        const res = await generateInviteCode()
        if (res.code === 0) {
          this.inviteCode = res.data.invite_code
          this.generateQRCode()
        }
      } catch (error) {
        console.error('生成邀请码失败:', error)
        this.inviteCode = 'INVITE123456'
      }
    },
    async openInviteModal() {
      try {
        const res = await getInviteQrcode()
        if (res) {
          this.inviteCode = res.invite_code
          this.qrcodeUrl = this.resolveUrl(res.qrcode_url)
        }
      } catch (e) {
        await this.generateInviteCode()
      }
      this.showQRCode = true
      this.$nextTick(() => { this.buildPoster() })
    },
    resolveUrl(url) {
      if (!url) return ''
      if (/^https?:\/\//i.test(url)) return url
      return APP_CONFIG.BASE_URL + url
    },
    
    // 生成二维码
    generateQRCode() {
      console.log('生成二维码:', this.inviteCode)
    },

    async buildPoster() {
      try {
        const info = await new Promise((resolve, reject) => {
          uni.getImageInfo({ src: this.qrcodeUrl, success: resolve, fail: reject })
        })
        const ctx = uni.createCanvasContext('invitePoster', this)
        const w = uni.upx2px(this.posterSizeRpx)
        const h = w // 正方形海报
        ctx.setFillStyle('#FFFFFF')
        ctx.fillRect(0, 0, w, h)
        // 顶部标题与邀请码
        ctx.setFillStyle('#333333')
        ctx.setFontSize(uni.upx2px(28))
        const title = '邀请您加入亦通查'
        const titleWidth = ctx.measureText(title).width
        ctx.fillText(title, (w - titleWidth) / 2, uni.upx2px(60))
        ctx.setFillStyle('#999999')
        ctx.setFontSize(uni.upx2px(24))
        const codeText = '邀请码：' + (this.inviteCode || '')
        const codeWidth = ctx.measureText(codeText).width
        ctx.fillText(codeText, (w - codeWidth) / 2, uni.upx2px(100))

        // 计算二维码区域（居中且上下留白）
        const topPad = uni.upx2px(140)
        const bottomPad = uni.upx2px(120)
        let qrSize = h - topPad - bottomPad
        qrSize = Math.max(uni.upx2px(320), Math.min(qrSize, uni.upx2px(480)))
        const qrX = Math.floor((w - qrSize) / 2)
        const qrY = topPad
        ctx.drawImage(info.path, qrX, qrY, qrSize, qrSize)

        // 底部提示
        ctx.setFillStyle('#666666')
        ctx.setFontSize(uni.upx2px(26))
        const tip = '长按以识别'
        const tipWidth = ctx.measureText(tip).width
        ctx.fillText(tip, (w - tipWidth) / 2, qrY + qrSize + uni.upx2px(60))
        ctx.draw(false, () => {})
      } catch (e) {}
    },

    savePoster() {
      const w = uni.upx2px(this.posterSizeRpx)
      const h = w
      uni.canvasToTempFilePath({
        canvasId: 'invitePoster',
        destWidth: w,
        destHeight: h,
        success: (res) => {
          const path = res.tempFilePath
          uni.saveImageToPhotosAlbum({
            filePath: path,
            success: () => { uni.showToast({ title: '已保存到相册', icon: 'success' }) },
            fail: () => { uni.showToast({ title: '保存失败', icon: 'none' }) }
          })
        },
        fail: () => { uni.showToast({ title: '生成海报失败', icon: 'none' }) }
      }, this)
    },
    
    // 复制邀请码
    copyInviteCode() {
      uni.setClipboardData({
        data: this.inviteCode,
        success: () => {
          this.$u.toast('邀请码已复制')
        }
      })
    },
    
    // 分享邀请
    shareInvite() {
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        type: 0,
        href: `${this.$u.config.baseUrl}/invite?code=${this.inviteCode}`,
        title: '邀请您注册使用',
        summary: '快来加入我们吧！',
        imageUrl: '/static/logo.png'
      })
    },
    
    // 跳转到提现页面
    goToWithdraw() {
      this.$u.route('/pages/user/withdraw/index')
    },
    
    // 跳转到账单明细
    goToBillDetail() {
      this.$u.route('/pages/user/commission')
    },
    
    // 查看规则
    viewRules() {
      this.$u.route('/pages/article/detail?id=1')
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      return this.$u.timeFormat(time, 'yyyy-mm-dd')
    },
    buildFallbackCommission(count) {
      const samples = [
        { avatar: '/static/images/default-avatar.png', nickname: '恭喜会员 李*天', description: '成功获得返利 月度会员', amount: '88.00' },
        { avatar: '/static/images/default-avatar.png', nickname: '恭喜会员 王*程', description: '成功获得返利 年度会员', amount: '218.00' },
        { avatar: '/static/images/default-avatar.png', nickname: '恭喜会员 赵*敏', description: '成功获得返利 三年会员', amount: '1093.00' },
        { avatar: '/static/images/default-avatar.png', nickname: '恭喜会员 陈*平', description: '成功获得返利 月度会员', amount: '99.00' },
        { avatar: '/static/images/default-avatar.png', nickname: '恭喜会员 孙*宇', description: '成功获得返利 年度会员', amount: '264.00' },
        { avatar: '/static/images/default-avatar.png', nickname: '恭喜会员 周*亮', description: '成功获得返利 三年会员', amount: '2508.00' }
      ]
      const result = []
      for (let i = 0; i < count; i++) {
        result.push(samples[i % samples.length])
      }
      return result
    }
  }
}
</script>

<style scoped>
/* 页面容器 */
.invite-page {
  min-height: 100vh;
  background: #f4f3f8;
  padding-bottom: 120rpx;
}

/* 滚动容器 */
.scroll-container {
  height: calc(100vh - 88rpx - 120rpx);
}

.nav-image {
  width: 40rpx;
  height: 40rpx;
}

.expand-image {
  width: 32rpx;
  height: 32rpx;
}

.close-image {
  width: 48rpx;
  height: 48rpx;
}

/* 信息面板区域 */
.info-panels {
  display: flex;
  gap: 20rpx;
  margin: 20rpx;
}

.panel {
  flex: 1;
  background: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
}

/* 左侧面板 */
.left-panel {
  display: flex;
  flex-direction: column;
  align-items: left;
}

.left-panel .panel-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 50rpx;
}

.amount {
  font-size: 60rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 50rpx;
}

.panel-buttons {
  display: flex;
  gap: 10rpx;
  width: 100%;
}

.btn-outline, .btn-primary, .rules-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
}

.btn-icon { width: 28rpx; height: 28rpx; }

.btn-outline {
  flex: 1;
  text-align: center;
  padding: 10rpx 5rpx;
  border: 2rpx solid #ea4148;
  color: #ea4148;
  border-radius: 10rpx;
  font-size: 26rpx;
}

.btn-primary {
  flex: 1;
  text-align: center;
  padding: 10rpx 5rpx;
  background: linear-gradient(to right, #ff767a, #ea4148);
  color: #ffffff;
  border-radius: 10rpx;
  font-size: 26rpx;
}

/* 右侧面板 */
.right-panel .panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.right-panel .panel-title {
  font-size: 28rpx;
  color: #333;
}

.rules-btn {
  background: #fcf2f3;
  color: #f3575d;
  padding: 12rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.stats-grid {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.stat-row {
  display: flex;
  gap: 30rpx;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #9b9b9b;
}

/* 佣金返利面板 */
.commission-panel {
  margin: 20rpx;
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
}

.commission-panel .panel-title {
  display: flex;
  align-items: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.title-bar {
  height: 30rpx;
  line-height: 30rpx;
  border-left: 6rpx solid #ea4148;
  padding-left: 15rpx;
}

.commission-scroll {
  height: 200rpx;
  overflow: hidden;
  position: relative;
}

.commission-list {
  position: absolute;
  width: 100%;
  transition: transform 0.1s linear;
}

.commission-item {
  display: flex;
  align-items: center;
  padding: 15rpx 0;
  height: 60rpx;
}

.user-avatar {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.commission-info {
  flex: 1;
  display: flex;
  align-items: center;
}

.commission-line {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #333;
}

.user-name {
  font-size: 26rpx;
  color: #333;
  margin-right: 12rpx;
}

.commission-desc {
  font-size: 26rpx;
  color: #333;
  margin-right: 8rpx;
}

.commission-amount {
  font-size: 28rpx;
  font-weight: bold;
  color: #f49e29;
  margin: 0 6rpx;
}

.commission-unit {
  font-size: 26rpx;
  color: #333;
}

/* 我的邀请面板 */
.invite-panel {
  margin: 20rpx;
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
}

.invite-panel .panel-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  cursor: pointer;
}

.expand-btn {
  transition: transform 0.3s ease;
}

.expand-btn.expanded {
  transform: rotate(180deg);
}

.invite-list {
  max-height: 300rpx;
  overflow: hidden;
  transition: max-height 0.3s ease;
}

.invite-list.expanded {
  max-height: none;
}

.invite-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.invite-item:last-child {
  border-bottom: none;
}

.invite-row {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.user-name {
  font-size: 28rpx;
  color: #333;
}

.invite-time {
  font-size: 24rpx;
  color: #888888;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60rpx 20rpx;
  color: #999;
  font-size: 28rpx;
}

/* 底部间距 */
.bottom-space {
  height: 40rpx;
}

/* 固定底部按钮 */
.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
  z-index: 100;
}

.invite-btn {
  width: 100%;
  text-align: center;
  padding: 28rpx 0;
  background: linear-gradient(to right, #ff767a, #ea4148);
  color: #ffffff;
  border-radius: 25rpx;
  font-size: 32rpx;
  font-weight: bold;
}

/* 二维码弹窗 */
.qr-popup {
  width: 600rpx;
  background: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
}

.qr-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.qr-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.qr-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 30rpx;
}

.qr-code {
  width: 200px;
  height: 200px;
  border: 1rpx solid #f0f0f0;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  overflow: hidden;
}

.invite-code {
  font-size: 24rpx;
  color: #999;
  background: #f5f5f5;
  padding: 12rpx 20rpx;
  border-radius: 20rpx;
  margin-bottom: 15rpx;
}

.qr-desc {
  font-size: 28rpx;
  color: #666;
}

.qr-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.qr-btn {
  flex: 1;
  text-align: center;
  padding: 24rpx;
  border-radius: 25rpx;
  font-size: 28rpx;
  font-weight: bold;
  background: #f5f5f5;
  color: #666;
}

.qr-btn.primary {
  background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
  color: #ffffff;
}
</style>
